import { getStorage, showTost, setStorage, checkLogin } from "./common";
import { baseURL } from "./base_url";
import useStore from "../stores/index";

const request = (
  url: string,
  data?: object | string,
  method?: "GET" | "POST" | "DELETE"
) => {
  const promise = new Promise((resolve, reject) => {
    const store = useStore();
    let delData = "";
    if (typeof data !== "string") {
      for (let key in data) {
        if (data.hasOwnProperty(key)) {
          delData += `${key}=${data[key]}`;
        }
      }
    }
    uni.request({
      url: method === "DELETE" ? baseURL + url + "?" + delData : baseURL + url,
      data: method === "DELETE" ? {} : data,
      method: method || "GET",
      header: {
        // user_id: getStorage('userId') || '',
        Authorization: getStorage("token") || "",
      },
      success: (res: { data: any }) => {
        if (res && (res.data.code === 401 || res.data.code === 601)) {
          if (store.isLoginModal) {
            uni.showToast({
              title: "登录状态失效，请切换账号",
              icon: "none",
              mask: true,
            });
            const userList = getStorage("userList");
            const token = getStorage("token");
            const newList = userList.filter(
              (i: { token: any }) => i.token !== token
            );
            setStorage("userList", newList);
            store.setIsLoginModal(false);
            store.loginOut();
            return;
          }

          store.loginOut();
          showTost("登录过期，请登陆", async () => {
            await checkLogin();
          });
          store.setIsLogin(false);
          return;
        }

        if (res && res.data.code !== 200) {
          reject(res);
          uni.showToast({
            icon: "none",
            title: res?.data?.msg || "系统异常",
          });
          return;
        }
        resolve(res.data);
      },
      fail: (err) => {
        console.log(err, "eeerr");
        reject(err);
      },
    });
  });

  return promise;
};

export default request;
